package org.nlp2rdf.navigator.component.resource.maps;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.dllearner.utilities.Files;
import org.nlp2rdf.navigator.component.exception.ComponentInitException;

import com.ibm.icu.util.StringTokenizer;

/**
 * Default separator is \t uri\tlabel
 * 
 * @author Sebastian Hellmann <hellmann@informatik.uni-leipzig.de>
 * 
 */
public class MapFromFile extends AbstractMap implements IMap {
	private static final Logger logger = Logger.getLogger(MapFromFile.class);

	private Set<String> fileNames;
	private String separator = "\t";

	@Override
	protected void _init() throws ComponentInitException {
		myMap = new HashMap<String, String>();
		for (String file : fileNames) {
			Map<String, String> tmp = loadLabels(componentConfig.getPathModifier() + file);
			logger
					.debug("loaded " + tmp.size() + " entries from " + componentConfig.getPathModifier()
							+ file);
			myMap.putAll(tmp);
		}

	}

	private Map<String, String> loadLabels(String fileName) throws ComponentInitException {
		Map<String, String> labels = new HashMap<String, String>();
		try {
			String[] l = Files.readFileAsArray(new File(fileName));
			for (int i = 0; i < l.length; i++) {
				try {
					StringTokenizer st = new StringTokenizer(l[i], separator);
					String uri = st.nextToken();
					String label = st.nextToken();
					labels.put(uri, label);
				} catch (Exception e) {
					logger.error("skipping misformed line in " + fileName);

				}
			}
		} catch (FileNotFoundException e) {
			String msg = "File not found " + fileName + "\n" + e.getMessage();
			logger.error(msg, e);
			throw new ComponentInitException(msg, e);
		} catch (IOException e) {
			logger.error("", e);
			throw new ComponentInitException(e);
		}
		return labels;

	}

	public void setFileNames(Set<String> fileNames) {
		this.fileNames = fileNames;
	}

}
